import React, { useState, forwardRef, useImperativeHandle, useEffect } from 'react';
import { Form, Input, Select, Modal, message } from 'antd';
import { env } from '@/utils/data';
import { getAllProjects } from '@/services/client/setenv';
import { addSystemApi } from '@/request/system';
import MyModal from '@/components/modal';

const SetEnv = ({ handleSubmit }, ref) => {
  const [form] = Form.useForm();
  const [open, setOpen] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [projects, setProjects] = useState<any[]>([]);
  const [envList, setEnvList] = useState<any[]>([]);
  const handleOk = async () => {
    const res = await form.validateFields();
    const params = {
      ...res,
      isEdit,
    };
    const result: any = await addSystemApi(params);
    if (result) {
      message.success('保存成功');
      handleSubmit();
      setOpen(false);
      form.resetFields();
    } else {
      const ret = result;
      message.error(ret.message);
    }
  };
  useImperativeHandle(ref, () => ({
    handleOpen(type: boolean, record: any) {
      setIsEdit(type);
      setOpen(true);
      if (type) {
        form.setFieldsValue(record);
        const currentProject = projects.find((t) => t._id === record.projectId);
        if (currentProject && currentProject.envs) {
          setEnvList(env.filter((t) => currentProject.envs.includes(t.value)));
        }
      }
    },
  }));

  const handleProjectChange = (value, option) => {
    setEnvList(env.filter((t) => option.envs.includes(t.value)));
    form.setFieldValue('gitlabName', option.name);
    form.setFieldValue('env', '');
  };

  useEffect(() => {
    getAllProjects()
      .then((data: any) => {
        setProjects(data.filter((t) => t.envs && t.envs.length > 0));
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);
  return (
    <div>
      <MyModal
        width={600}
        open={open}
        title={isEdit ? '编辑' : '新增'}
        onCancel={() => {
          form.resetFields();
          setOpen(false);
        }}
        onOk={() => {
          handleOk();
        }}
      >
        <div className="set-env">
          <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} layout="horizontal" form={form}>
            <Form.Item name="_id" colon={false} hidden>
              <Input readOnly />
            </Form.Item>
            <Form.Item name="gitlabName" colon={false} hidden>
              <Input readOnly />
            </Form.Item>
            <Form.Item label="项目名称" colon={false} name="projectId" rules={[{ required: true, message: '请选择项目名称' }]}>
              <Select
                placeholder="请选择项目"
                options={projects}
                showSearch
                fieldNames={{ label: 'name', value: '_id' }}
                filterOption={(input, option) => {
                  const label = option.name as string;
                  return label?.includes(input?.trim());
                }}
                onChange={handleProjectChange}
              />
            </Form.Item>
            <Form.Item label="显示名称" colon={false} name="systemName">
              <Input placeholder="设置项目显示的名称" />
            </Form.Item>
            <Form.Item label="访问环境" name="env" colon={false} rules={[{ required: true, message: '请选择访问环境' }]}>
              <Select options={envList}></Select>
            </Form.Item>
            <Form.Item label="访问地址" colon={false} name="webUrl" rules={[{ required: true, message: '请输入访问地址' }]}>
              <Input />
            </Form.Item>
            <Form.Item label="jenkins地址" colon={false} name="jenkinsUrl" style={{ marginBottom: '0' }} rules={[{ required: true, message: '请输入访问地址' }]}>
              <Input />
            </Form.Item>
          </Form>
        </div>
      </MyModal>
    </div>
  );
};
export default forwardRef(SetEnv);
